package com.eci.example.webapi;

import com.eci.common.asset.algorithm.SnowFlake;
import com.eci.common.asset.core.R;
import com.eci.context.context.lock.RedissonLocker;
import com.eci.context.util.BeanUtil;
import com.eci.example.domain.entity.Example;
import com.eci.example.domain.repository.ExampleRepository;
import com.eci.example.feign.ExampleFeign;
import com.eci.example.vo.ExampleReq;
import com.eci.example.vo.ExampleRsp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("example")
@Api(tags = "基础配置/定时任务")
@Slf4j
@RefreshScope
public class ExampleController implements ExampleFeign {

    // nacos 注册中心
    @Value("${uuu}")
    String userName;

    @Autowired
    ExampleRepository exampleRepository;


    @GetMapping("getName")
    @ApiOperation(value = "分页列表", notes = "固定按顺序号排序,不支持自定义排序功能")
    @ResponseBody
    public R<ExampleRsp> getName() {
        ExampleRsp rsp = ExampleRsp.builder().name(userName).build();
        return R.ok(rsp);
    }

    @PostMapping("add")
    @ApiOperation(value = "分页列表", notes = "固定按顺序号排序,不支持自定义排序功能")
    @Override
    @ResponseBody
    public R<ExampleRsp> add(@RequestBody ExampleReq req) {
        Example example = Example.builder().id(SnowFlake.getInstance().nextId()).amount(req.getAmount()).name(req.getName()).build();
        exampleRepository.save(example);
        ExampleRsp rsp = BeanUtil.copy(example, ExampleRsp.class);
        return R.ok(rsp);
    }

    @Autowired
    RedissonLocker redissonLocker;

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @PostMapping("lock")
    @ApiOperation(value = "分页列表", notes = "固定按顺序号排序,不支持自定义排序功能")
    @ResponseBody
    public R<ExampleRsp> lock() {
        redissonLocker.lock("tom");
        redissonLocker.unlock("tom");
        return R.ok(ExampleRsp.builder().build());
    }

}
